package com.gk.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.study.DTO.TargetIdDTO;
import com.gk.study.Vo.ChatListVO;
import com.gk.study.entity.ChatMessage;
import com.gk.study.entity.User;
import com.gk.study.mapper.ChatMessageMapper;
import com.gk.study.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService  {
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private UserServiceImpl userService;

    @Transactional
    @Override
    public void saveMessage(ChatMessage message) {
        chatMessageMapper.insert(message);
    }

    @Override
    public List<ChatMessage> getChatHistory(String user1Id, String user2Id) {
        return chatMessageMapper.selectList(new QueryWrapper<ChatMessage>()
                .and(wrapper -> wrapper
                        .eq("sender_id", user1Id).eq("receiver_id", user2Id)
                        .or()
                        .eq("sender_id", user2Id).eq("receiver_id", user1Id)
                )
                .orderByAsc("create_time")
        );
    }


    @Override
    public List<ChatListVO> getChatList(String currentUserId) {
        List<String> targetIds = chatMessageMapper.selectTargetIds(currentUserId);

        return targetIds.stream().map(targetId -> {

            User user = userService.getUserDetail(targetId);

            ChatListVO vo = new ChatListVO();
            vo.setTargetId(targetId);
            vo.setTargetName(user.getNickname());  // 设置昵称
            vo.setAvatar(user.getAvatar());        // 设置头像路径
            vo.setLastMessage(getLastMessage(currentUserId, targetId));

            return vo;
        }).collect(Collectors.toList());
    }


    private ChatMessage getLastMessage(String user1, String user2) {
        return chatMessageMapper.selectOne(new QueryWrapper<ChatMessage>()
                .and(wrapper -> wrapper
                        .eq("sender_id", user1).eq("receiver_id", user2)
                        .or()
                        .eq("sender_id", user2).eq("receiver_id", user1)
                )
                .orderByDesc("create_time")
                .last("LIMIT 1")
        );
    }




}